﻿using LitJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TopVisionLog;
using TopVisionVideoStream.TopVisionCenter;

namespace TopVisionVideoStream.Mananger
{
    public static class TVCMeetingRoomManager
    {
        private static List<ConfVideo> meetingRooms;

        public static List<ConfVideo> MeetingRooms
        {
            get
            {
                if (meetingRooms == null) meetingRooms = new List<ConfVideo>();
                return meetingRooms;
            }

            set { meetingRooms = value; }
        }

        private static bool isInited = false;

        public static bool IsDispose = false;

        /// <summary>
        /// 更新视频列表的间隔(默认3秒)
        /// </summary>
        public static TimeSpan Interval = TimeSpan.FromSeconds(3);

        public static void Init(bool fromTVCenter)
        {
            if (isInited) return;

            IsDispose = false;

            isInited = true;

            if (fromTVCenter)
            {
                TVCUpdate();
            }
            else
            {

            }
        }

        private static async void TVCUpdate()
        {
            if (isInited)
            {
                while (!IsDispose)
                {
                    await UpdateMeetingRoomsAsync();

                    await Task.Delay(Interval);
                }
            }
        }

        private static async Task UpdateMeetingRoomsAsync()
        {
            try
            {
                TVCConferenceQueryroomsModel model = new TVCConferenceQueryroomsModel();

                model.companyid = Configuration.CompanyID;

                model.status = "1";

                TVCenter center = new TVCenter();

                TVCenterResponse result = null;

                Task.Factory.StartNew(async () =>
                {
                    result = await center.ConferenceQueryrooms(model);
                });

                while (result == null)
                {
                    await Task.Delay(100);
                }

                if (result.success)
                {
                    var confsInfo = result.data.confInfo;

                    string json = JsonMapper.ToJson(confsInfo);

                    MeetingRooms = JsonMapper.ToObject<List<ConfVideo>>(json);
                }
            }
            catch (Exception ex)
            {
                TVLog.WriteLine("ERR UpdateMeetingRoomsAsync : " + ex.Message);
            }
        }

        public static void Dispose()
        {
            IsDispose = true;

            isInited = false;
        }
    }
}
